#include <string>
#include <chrono>
#include <thread>
#include <iostream>

#include <zmq.hpp>

// zmq的router-dealer模式，router 会接收到 两 frame 的消息 ，第一帧是 发送端的 标识。第二帧才是 真正的数据。
// 同时 router 回复的时候，也要 发送两 frame

int main() {
    using namespace std::chrono_literals;

    // initialize the zmq context with a single IO thread
    zmq::context_t context{1};

    zmq::socket_t socket{context, zmq::socket_type::router};
    socket.bind("tcp://127.0.0.1:9012");

    zmq_pollitem_t items[] = {
            {socket, 0, ZMQ_POLLIN, 0}
    };
    zmq::message_t addr;
    for (;;) {
        int rc = zmq::poll(items, 1, 5000);

        if (rc == -1) {
            break;
        }

        if (items[0].revents & ZMQ_POLLIN) {

            zmq::message_t request;
            socket.recv(addr, zmq::recv_flags::none);
            char *id = (char *) addr.data();
            int size = addr.size();

            socket.recv(request, zmq::recv_flags::none);
            std::cout << "Received " << request.to_string() << std::endl;

        }
        zmq::message_t msg;
//       // msg.copy(addr);
        msg.rebuild("api-gateway-01", 14);
//        socket.send(zmq::buffer("api-gateway-01"), zmq::send_flags::sndmore);
        socket.send(msg, zmq::send_flags::sndmore);
        std::string s = "who am i?";
        socket.send(zmq::buffer(s), zmq::send_flags::dontwait);
        std::cout << "send" << std::endl;
    }

    return 0;
}